package com.wxxymaker.edu.service;

import com.blade.ioc.annotation.Bean;
import com.blade.kit.CollectionKit;
import com.wxxymaker.edu.model.entity.CourseSpecialty;
import com.wxxymaker.edu.model.entity.CourseSubject;
import io.github.biezhi.anima.Anima;
import io.github.biezhi.anima.core.AnimaQuery;
import io.github.biezhi.anima.core.Joins;
import io.github.biezhi.anima.enums.OrderBy;
import io.github.biezhi.anima.page.Page;

/**
 * @AUTHOR soft
 * @DATE 2018/10/16 16:51
 * @DESCRIBE 课程所属学科
 */
@Bean
public class CourseSubjectService implements Service<CourseSubject> {

    /**
     * 获取学科分页
     * @param csid 专业id
     */
    public Page<CourseSubject> page(Integer csid, int page, int size) {
        AnimaQuery<CourseSubject> order = Anima.select().from(CourseSubject.class)
                .join(Joins.with(CourseSpecialty.class)
                        .as(CourseSubject::getSpecialty)
                        .on(CourseSubject::getSpecialtyId, CourseSpecialty::getId))
                .order(CourseSubject::getTime, OrderBy.DESC);
        if (csid != null && csid > 0) order.where(CourseSubject::getSpecialtyId, csid);
        Page<CourseSubject> page1 = order.page(page, size);
        if (CollectionKit.isNotEmpty(page1.getRows())) {
            return page1;
        }
        return null;
    }


    public Page<CourseSubject> sp_page(int specialtyId, int page, int size) {
        Page<CourseSubject> page1 = Anima.select().from(CourseSubject.class)
                .where(CourseSubject::getSpecialtyId,specialtyId)
                .order(CourseSubject::getTime, OrderBy.DESC)
                .page(page, size);
        if (CollectionKit.isNotEmpty(page1.getRows())) {
            return page1;
        }
        return null;
    }


    @Override
    public CourseSubject add(CourseSubject courseSubject) {
        Integer integer = courseSubject.save().asInt();
        if (integer > 0) {
            courseSubject.setId(integer);
            return courseSubject;
        }
        return null;
    }

    @Override
    public CourseSubject delete(Object pk) {
        CourseSubject courseSubject = byId(pk);
        if (courseSubject != null) {
            courseSubject.delete();
            return courseSubject;
        }
        return null;
    }
    //    指定学科下的课程数
    public long count(int spid) {
        long count = Anima.select().from(CourseSubject.class)
                .where(CourseSubject::getSpecialtyId,spid)
                .count();
        return count;
    }
    @Override
    public boolean change(CourseSubject courseSubject) {
        Integer id = courseSubject.getId();
        if (id != null && id > 0) {
            return courseSubject.update() > 0;
        }
        return false;
    }

    @Override
    public CourseSubject byId(Object pk) {
        return Anima.select().from(CourseSubject.class).byId(pk);
    }
}
